package com.cynen.javlib.job;

import com.cynen.javlib.task.PicScrap;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.Spider;

import java.io.*;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.function.Consumer;
import java.util.stream.Stream;

@Component
public class JavJob {

    @Value("${jav.init.url}")
    private  String initUrl;
    // 启动任务的定时任务.
    @Scheduled(initialDelay = 1000,fixedDelay = 5*1000)
    public void start_spider(){
        //读取文件.
        InputStream stream = JavJob.class.getClassLoader().getResourceAsStream("config.properties");
        Properties prop = new Properties();
        try {
            prop.load(stream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 为了获取外部配置的Cookie值.
        try {
            BufferedReader bufferedReader = new BufferedReader(new FileReader(prop.getProperty("cookie_file_path")));
            String readLine = bufferedReader.readLine();
            // String[] splits = readLine.split("=", 2);
            prop.setProperty("Cookie",readLine); // 不配置成键值对,直接存cookie值.
            bufferedReader.close();
        }catch (Exception e){
            System.out.println("cookie_file_path 配置文件异常");
        }

        // 构建Map
        Map<String,String> info = new HashMap<>();
        info.put("charset",prop.getProperty("charset"));
        info.put("userAgent",prop.getProperty("userAgent"));
        info.put("Cookie",prop.getProperty("Cookie"));
        info.put("Domain",prop.getProperty("Domain"));

        Spider.create(new PicScrap(info))
                .addUrl(initUrl)
                .thread(2)
                .run();

    }

    // @Scheduled(initialDelay = 1000,fixedDelay = 5*1000)
    public  void write_to(){
        // 先配置文件中写入数据.
        try {
            // 获取的是classpath路径.
            URL resource = JavJob.class.getClassLoader().getResource("");
            // System.out.println(resource.getPath());
            File file = new File(resource.getPath()+"config.properties");
            BufferedReader br = new BufferedReader(new FileReader(file));

            String line = br.readLine();
            System.out.println(line);
            br.readLine();


            // FileWriter fileWriter = new FileWriter(file);
            // fileWriter.append("Hello...");
            // fileWriter.flush();
            // fileWriter.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


}
